<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use Exception;

class ShopOrder extends CommonModel {
	protected $table = 'shop_order';
	
	//查询订单状态
    public function checkOrderStatus($order_sn){
        $order=DB::table('shop_order')->where(['order_sn'=>$order_sn])->first();
        $order_payment = ShopOrderPayment::where(['order_sn'=>$order_sn])->first();
        if($order_payment->pay_status==1 || $order->status!=1){
            $order_payment->status = 2;
            return $order_payment;
        }else{
            $order_payment->status =1;
            return $order_payment;
        }
    }

	public function getOrderStatus($type,$store_id){
        $wait_pay = self::where(['store_id'=>$store_id,'status'=>1,'is_store_del'=>0])->count();
        $wait_send =self::where(['store_id'=>$store_id,'status'=>2,'is_store_del'=>0])->count();
        $send =self::where(['store_id'=>$store_id,'status'=>3,'is_store_del'=>0])->count();
        $wait_refund = self::where(['store_id'=>$store_id,'status'=>1,'is_store_del'=>0])->count();
        $over = self::where(['store_id'=>$store_id,'status'=>5,'is_store_del'=>0])->count();
        $order_num = self::where(['store_id'=>$store_id,'is_store_del'=>0])->count();
        $return=array();
        switch ($type){
            case 1:
                $return=array(
                    '0'=>[
                        'name'=>'全部',
                        'status'=>0,
                        'value'=>$order_num
                    ],
                    '1'=>[
                        'name'=>'待付款',
                        'status'=>1,
                        'value'=>$wait_pay
                    ],
                    '2'=>[
                        'name'=>'待发货',
                        'status'=>2,
                        'value'=>$wait_send
                    ],
					'3'=>[
						'name'=>'已发货',
						'status'=>3,
						'value'=>$send
					],
                    '4'=>[
                        'name'=>'售后',
                        'status'=>7,
                        'value'=>$wait_refund
                    ],
                    '5'=>[
                        'name'=>'已完成',
                        'status'=>5,
                        'value'=>$over
                    ]
                );
                break;
            case 2:
                $return=array(
                    '0'=>[
                        'name'=>'全部',
                        'status'=>0,
                        'value'=>$order_num
                    ],
                    '1'=>[
                        'name'=>'待付款',
                        'status'=>1,
                        'value'=>$wait_pay
                    ],
                    '2'=>[
                        'name'=>'待派单',
                        'status'=>2,
                        'value'=>$wait_send
                    ],
                    '3'=>[
                        'name'=>'已完成',
                        'status'=>5,
                        'value'=>$over
                    ],

                );
                break;
        }
        return $return;
    }

    //获取商品详情
    public function detail(){
        $order_sn = $this->getAttribute('order_sn');
        $status = $this->getAttribute('status');
        $created_at = $this->getAttribute('created_at');
        $order_type = $this->getAttribute('order_type');
        $buyer_id = $this->getAttribute('buyer_id');
        $store_id = $this->getAttribute('store_id');
        $end_time = 0;

        //未付款订单结束时间
        if($status ==1 && $order_type!=4){
            if($order_type==1) {
                $deadline =  Config::key('order_seckill_deadline')->value('value');
            }else{
                $deadline =  Config::key('order_deadline')->value('value');
            }
            $end_time = date('Y-m-d H:i:s',(strtotime($created_at) + $deadline));
        }

        //订单商品处理
        $order_goods = ShopOrderGoods::where(['order_sn'=>$order_sn])
            ->select('goods_id','goods_spec','refund_status','goods_type','market_price','goods_name','store_id','goods_price','goods_image','goods_number')
            ->get()
            ->groupBy('store_id')
            ->toArray();
		$all_number = ShopOrderGoods::where(['order_sn'=>$order_sn])->count('*');
        foreach ($order_goods as $k=>$v){
            unset($order_goods[$k]);
            foreach ($v as $key=>$val){
                $v[$key]['goods_spec'] = $val['goods_spec']?:'';
            }
            $order_goods[$k]['goods_list'] = $v;
            $order_goods[$k]['store_id'] = $k;
            $store_info = ShopStore::getStoreDetailById($k);
            $order_goods[$k]['uid']  = $store_info->uid;
            $order_goods[$k]['store_name'] = $store_info->store_name;
            $order_goods[$k]['store_mobile'] = $store_info->store_mobile;

        }
		
        foreach ($order_goods as $key=>$val){
            $result[] = $val;
        }

        $buyer_name = ClientUser::where(['id'=>$buyer_id])->value('username');
        $store_logo = ShopStore::where(['id'=>$store_id])->value('store_logo');
        $this->setAttribute('store_list',$result);
        $this->setAttribute('store_logo',$store_logo);
        $this->setAttribute('buyer_name',$buyer_name);
		$this->setAttribute('all_number',$all_number);
		$this->setAttribute('end_time',$end_time);
	}

    //订单详情
    public function address(){
		
        $order_sn = $this->getAttribute('order_sn');
        $status = $this->getAttribute('status');
        $order_address = ShopOrderAddress::where(['order_sn'=>$order_sn])->select('mobile','name','remark','express_name','express_mobile','express_id','express_code','house_id','updated_at as address_time','address as address_remark')->first();
        //用户地址信息
        $user_address = collect([]);
        $user_address['mobile'] = $order_address->mobile;
        $user_address['name'] = $order_address->name;
        $user_address['address_remark'] = $order_address->address_remark;
        $user_address['address'] = House::where(['house_id'=>$order_address->house_id])->value('house_detail');
        //物流发货信息
        $express =  new \stdClass();

        if($status>=3) {
            $express->express_name = $order_address->express_name;
            $express->express_code = $order_address->express_code;
            $express->updated_at = $order_address->address_time;
            $express->express_mobile = $order_address->express_mobile;
            $express->express_id = $order_address->express_id;
        }

        $this->setAttribute('user_address',$user_address);
        $this->setAttribute('remark',$order_address->remark);
        $this->setAttribute('express',$express);
		
    }
	//商品详情
    public function store_address(){
		
        $order_sn = $this->getAttribute('order_sn');
        $status = $this->getAttribute('status');
        $order_type = $this->getAttribute('order_type');
		
        $order_address = ShopOrderAddress::where(['order_sn'=>$order_sn])->select('mobile','name','remark','express_name','express_code','house_id','updated_at as address_time','address as address_remark')->first();
		
		
		
        //用户地址信息
		 $user_address = collect([]);
		if($order_type==3 && $status==1){
			$address_info = House::where(['house_id'=>$order_address->house_id])->first();
			$village_name = HouseDistrict::where(['id'=>$address_info->village_id])->value('name');
			$partition_name = HouseDistrict::where(['id'=>$address_info->partition_id])->value('name');
			
			$user_address['mobile'] = mb_substr($order_address->mobile,0,3,'utf-8').'……';
			$user_address['name'] = mb_substr($order_address->name,0,2,'utf-8').'……';
			$user_address['address_remark'] = $order_address->address_remark?(mb_substr($order_address->address_remark,0,8,'utf-8').'……'):'';
			$user_address['address'] = $village_name.$partition_name.'……';
		}else{
			$address=House::where(['house_id'=>$order_address->house_id])->value('house_detail');
			$user_address['mobile'] = $order_address->mobile;
			$user_address['name'] = $order_address->name;
			$user_address['address_remark'] = $order_address->address_remark;
			$user_address['address'] = $address;
		}
       
        
        //物流发货信息
        $express =  new \stdClass();
        if($status>=3) {
            $express->express_name = $order_address->express_name;
            $express->express_code = $order_address->express_code;
            $express->updated_at = $order_address->address_time;
        }

        $this->setAttribute('user_address',$user_address);
        $this->setAttribute('remark',$order_address->remark);
        $this->setAttribute('express',$express);
		
    }
    //获取订单详情
    public function getOrderDetail($order_sn,$uid='',$store_id=''){
        return self::where(['order_sn'=>$order_sn])->when($uid,function($query) use ($uid){
            $query->where(['uid'=>$uid]);
        })->when($store_id,function ($query) use ($store_id){
            $query->where(['store_id'=>$store_id]);
        })->first();
    }

    //回滚库存
    public function rbackGoodsStock($order_sn){
        ShopOrderGoods::where(['order_sn'=>$order_sn])->get()->each(function($v,$k){
            if($v->goods_type==1){
                $update =ShopSeckillGoods::rbackGoodsStock($v->goods_id);
            }else if($v->goods_type==2){
                $update =ShopGroupGoods::rbackGoodsStock($v->goods_id,$v->goods_number);
            }else{
                $update =ShopGoods::rbackGoodsStock($v->goods_id,$v->goods_number);
            }
            if(!$update){
                throw new Exception('更新商品库存失败');
            }
        });
    }
    /**
     * 确认订单
     * @param $order_sn
     * @param $order_detail
     * @param $type
     * @return mixed
     */
    public function confirmOrder($order_sn,$uid,$type=1){
        $return=DB::transaction(function () use($order_sn,$uid,$type) {
            $order_detail = ShopOrder::getOrderDetail($order_sn,$uid);
            if(!$order_detail){
                throw new Exception('找不到订单');
            }
            if($order_detail->status!=3) {
                throw new Exception('当前状态下不能确认订单');
            }
            if($order_detail->order_type ==1 || $order_detail->order_type==2) {
                $status=5;
            }else{
                $status=4;
            }
            $return = ShopOrder::where(['order_sn' => $order_sn])->update(['status' => $status]);
            //插入日志
            if($type==1){
                $detail = '用户已经确认收货';
            }else{
                $detail = '系统已自动确认收货';
            }
            ShopOrderLog::createOrderLog($uid,$order_sn,$detail,$uid);
            //消息通知
            Message::message_push($order_detail->store_id,'order_confirm',$detail.'订单号：'.$order_sn,$order_sn,1);
            //增加销量
            //更新分成表状态
            ShopOrderSplit::confirmOrder($order_sn);
            return $return;
        });
        return $return;
    }
    public function createOrderSN(){
        $order_sn=DB::select("select seq() as order_sn")['0']->order_sn;
        return $order_sn;
    }
}